package cn.edu.imau.zy.dfs.controller;

import cn.edu.imau.zy.common.utils.StringUtils;
import cn.edu.imau.zy.common.utils.file.FileUtils;
import cn.edu.imau.zy.dfs.config.DfsConfig;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import cn.edu.imau.zy.common.annotation.LoginUser;
import cn.edu.imau.zy.common.core.entity.system.SysUser;
import cn.edu.imau.zy.common.core.entity.dfs.DfsFile;

import cn.edu.imau.zy.common.core.domain.R;
import cn.edu.imau.zy.common.core.controller.BaseController;
import cn.edu.imau.zy.dfs.service.IDfsFileService;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件 提供者
 *
 * @author wyz
 * @date 2020-10-31
 */
@Slf4j
@RestController
@RequestMapping("file")
public class DfsFileController extends BaseController {

    @Autowired
    private IDfsFileService dfsFileService;
    @Autowired
    private DfsConfig dfsConfig;

    /**
     * 入库上传请求
     */
    @PostMapping("upload")
    public R upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file == null) {
            throw new Exception("请选择上传文件");
        }
        try {
            DfsFile dfile = new DfsFile();
            dfile.setId(IdUtil.getSnowflake(2, 2).nextIdStr());
            dfile.setName(file.getOriginalFilename());
            dfile.setSuffix(file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")));
            dfile.setPath(dfsConfig.getPath() + dfile.getId() + dfile.getSuffix());
            dfile.setCreateBy(String.valueOf(getCurrentUserId()));
            // 上传文件路径
            File path = new File(dfsConfig.getPath());
            if (!path.exists()) {
                path.mkdirs();
            }
            FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(dfile.getPath()));
            dfsFileService.insertDfsFile(dfile);
            return R.ok().put("fileId", dfile.getId());
        } catch (Exception e) {
            log.error("上传文件失败", e);
            throw new Exception("上传文件失败");
        }
    }

    /**
     * 通用下载请求
     *
     * @param id 文件id
     */
    @GetMapping("download/{id}")
    public void download(@PathVariable("id") String id, HttpServletResponse response, HttpServletRequest request) {
        DfsFile dFile = dfsFileService.selectDfsFileById(id);
        try {
            if (null == dFile) {
                throw new Exception(StringUtils.format("文件不存在。 "));
            }
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, dFile.getName()));
            FileUtils.writeBytes(dFile.getPath(), response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 图片浏览
     */
    @RequestMapping("/img/{id}")
    public void img(@PathVariable("id") String id, HttpServletResponse response) {

        DfsFile dFile = dfsFileService.selectDfsFileById(id);
        Map<String, Object> type = new HashMap<>();
        type.put(".jpg", "image/jpeg");
        type.put(".jpeg", "image/jpeg");
        type.put(".jpe", "image/jpeg");
        type.put(".gif", "image/gif");
        type.put(".png", "image/png");
        type.put(".bmp", "image/bmp");

        if (type.containsKey(dFile.getSuffix().toLowerCase())) {
            FileInputStream fis = null;

            try {
                fis = new FileInputStream(dFile.getPath());
                response.setHeader("Content-Type", type.get(dFile.getSuffix().toLowerCase()).toString());
                OutputStream out = response.getOutputStream();

                FileCopyUtils.copy(fis, out);

                out.flush();

                out.close();
            } catch (Exception e) {
                log.error(e.getMessage());
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        log.error(e.getMessage());
                    }
                }
            }
        }

    }

    /**
     * 查询${tableComment}
     */
    @GetMapping("get/{id}")
    public DfsFile get(@PathVariable("id") String id) {
        return dfsFileService.selectDfsFileById(id);
    }

    /**
     * 查询文件列表
     */
    @GetMapping("listByIds/{ids}")
    public R list(@PathVariable String ids) {
        return R.data(dfsFileService.selectDfsFileListByIds(ids));
    }

    /**
     * 查询文件列表
     */
    @GetMapping("list")
    public R list(DfsFile dfsFile) {
        startPage();
        return result(dfsFileService.selectDfsFileList(dfsFile));
    }


    /**
     * 新增保存文件
     */
    @PostMapping("save")
    public R addSave(@RequestBody DfsFile dfsFile, @LoginUser SysUser user) {
        dfsFile.setCreateBy(user.getUserId().toString());
        return toAjax(dfsFileService.insertDfsFile(dfsFile));
    }

    /**
     * 修改保存文件
     */
    @PostMapping("update")
    public R editSave(@RequestBody DfsFile dfsFile, @LoginUser SysUser user) {
        dfsFile.setUpdateBy(user.getUserId().toString());
        return toAjax(dfsFileService.updateDfsFile(dfsFile));
    }

    /**
     * 删除${tableComment}
     */
    @PostMapping("remove")
    public R remove(String ids) {
        return toAjax(dfsFileService.deleteDfsFileByIds(ids));
    }

}
